package com.qg.rta.support.channel;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qg.rta.annnotions.ProductType;
import com.qg.rta.constant.ProductChannelConstant;
import com.qg.rta.dto.request.RtaCommonRequest;
import com.qg.rta.dto.zhihu.request.ZhiHuProto;
import com.qg.rta.dto.zhihu.request.ZhiHuRtaRequest;
import com.qg.rta.modules.dto.RtaConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


@Component
@ProductType(ProductChannelConstant.ZHI_HU)
@Slf4j
public class ZhiHuReport extends AbstractReport{

    @Override
    public boolean rtaReq(RtaCommonRequest rtaCommonRequest, RtaConfigDTO rtaConfigDTO) {

        ZhiHuRtaRequest.Builder builder = ZhiHuRtaRequest.newBuilder();
        if(StringUtils.isNotBlank(rtaCommonRequest.getImeiSum()) && !rtaCommonRequest.getImeiSum().contains("__")) {
            builder.setImeiMd5(rtaCommonRequest.getImeiSum());
        }

        if(StringUtils.isNotBlank(rtaCommonRequest.getOaid()) && !rtaCommonRequest.getOaid().contains("__")) {
            builder.setOaid(rtaCommonRequest.getOaid());
        }

        if(StringUtils.isNotBlank(rtaCommonRequest.getOaidSum()) && !rtaCommonRequest.getOaidSum().contains("__")) {
            builder.setOaidMd5(rtaCommonRequest.getOaidSum());
        }
        if(StringUtils.isNotBlank(rtaCommonRequest.getCaidSum()) && !rtaCommonRequest.getCaidSum().contains("__")) {
            builder.setCaid(rtaCommonRequest.getCaidSum());
        }
        if(StringUtils.isNotBlank(rtaCommonRequest.getCaid()) && !rtaCommonRequest.getCaid().contains("__")) {
            builder.addRtaIds(rtaCommonRequest.getCaid());
        }
        ZhiHuRtaRequest zhiHuRtaRequest = builder.build();

        byte[] byteArray = zhiHuRtaRequest.toByteArray();
        HttpRequest post = HttpUtil.createPost(rtaConfigDTO.getProductUrl());
        post.keepAlive(true);
        post.header("Content-Type", "application/x-protobuf");
        post.charset("UTF-8");
        HttpRequest body = post.body(byteArray);
        String result = body.execute().body();
        JSONObject resultObject = JSONObject.parseObject(result);
        if(resultObject.containsKey("matched")){
            return resultObject.getBoolean("matched");
        }
        return false;
    }
}
